<?php
namespace App\Http\Controllers\Client\Auth;

use App\Http\Controllers\ClientController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AuthAccessTokenController extends ClientController
{

    public function index()
    {

        $all = $this->all;

        $code = $all['code'];
        $appid = env('WECHAT_OFFICIAL_ACCOUNT_APPID');
        $secret = env('WECHAT_OFFICIAL_ACCOUNT_SECRET');

        try {
            // 网页Oauth2 token
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
            $content = file_get_contents($url);
            $oauth2 = json_decode($content, true);
            if (isset($oauth2['errcode'])) {
                Log::debug('认证失败：',['appid'=>$appid,'secret'=>$secret,'code'=>$code]);
                throw new \Exception(json_encode($oauth2));
            }

            // 拉取用户信息
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $oauth2['access_token'] . "&openid=".$oauth2['openid']."&lang=zh_CN";
            $content = file_get_contents($url);
            $wechatMessage = json_decode($content, true);
            if (isset($wechatMessage['errcode'])) {
                Log::debug('认证失败2',['appid'=>$appid,'secret'=>$secret,'code'=>$code,'oauth2'=>$oauth2]);
                throw new \Exception(json_encode($wechatMessage));
            }
        } catch (\Exception $e) {
            Log::error(AuthAccessTokenController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '用户授权失败');
        }

        try{
            //查询是否已存在
            $userMessage = DB::table('lottery_users')->where('openid','=',$wechatMessage['openid'])->first();

            if($userMessage === null){ // 不存在用户：新建
                $we_id = DB::table('lottery_users')->insertGetId([
                    'openid'=>$wechatMessage['openid'],
                    'nickname'=>$wechatMessage['nickname'],
                    'sex'=>$wechatMessage['sex'],
                    'country'=>$wechatMessage['country'],
                    'province'=>$wechatMessage['province'],
                    'city'=>$wechatMessage['city'],
                    'headimgurl'=>$wechatMessage['headimgurl'],
                    'unionid'=>$wechatMessage['unionid']??'',
                ]);
                $userMessage['we_id'] = $we_id;
            }else{ // 更新用户
                $userMessage = json_decode(json_encode($userMessage),true);
                $we_id = $userMessage['we_id'];
                DB::table('lottery_users')->where('we_id',$we_id)->update([
                    'nickname'=>$wechatMessage['nickname'],
                    'sex'=>$wechatMessage['sex'],
                    'country'=>$wechatMessage['country'],
                    'province'=>$wechatMessage['province'],
                    'city'=>$wechatMessage['city'],
                    'headimgurl'=>$wechatMessage['headimgurl'],
                ]);
            }
            return $this->setReturnJson(0,'登录成功',['token'=>encrypt($we_id)]);
        }catch (\Exception $e){
            Log::error(AuthAccessTokenController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'用户授权失败');
        }

    }

}
